package com.xoa.dev.dingding.service;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.dingtalk.oapi.lib.aes.DingTalkJsApiSingnature;
import com.taobao.api.ApiException;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.dingdingManage.UserDDMapMapper;
import com.xoa.dao.users.OrgManageMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dev.dingding.model.UserDingDing;
import com.xoa.model.common.SysPara;
import com.xoa.model.department.Department;
import com.xoa.model.dingdingManage.DingdingUpdateDept;
import com.xoa.model.dingdingManage.DingdingUser;
import com.xoa.model.dingdingManage.UserDDMap;
import com.xoa.model.users.OrgManage;
import com.xoa.model.users.Users;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.dataSource.ContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by zhangHangNing on 2019/8/2.
 */
@Service
public class DingdingService {

    @Autowired
    private SysParaMapper sysParaMapper;

    @Autowired
    private UserDDMapMapper userDDMapMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private OrgManageMapper orgManageMapper;

    // 企业凭证
    private String ACCESS_TOKEN = "";

    // accessToken 生成时间（两个小时有效期
    private Long accessToken_TimeLimit = new Date().getTime();


    /**
     * @作者: 张航宁
     * @时间: 2019/8/5
     * @说明: 获取AccessToken
     */
    public String getAccessToken(){
        Long CurTimeLimit = new Date().getTime();
        if(ACCESS_TOKEN == "" || (CurTimeLimit-accessToken_TimeLimit)/1000 >7000){

            SysPara appKeyPara = sysParaMapper.querySysPara("DINGDINGQY_APPKEY");
            SysPara appSecretPara = sysParaMapper.querySysPara("DINGDINGQY_APPSECRET");

            DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(appKeyPara.getParaValue());
            request.setAppsecret(appSecretPara.getParaValue());
            request.setHttpMethod("GET");

            try {
                OapiGettokenResponse response = client.execute(request);
                if(response.getErrcode()==0){
                    ACCESS_TOKEN = response.getAccessToken();
                }
            } catch (ApiException e) {
                e.printStackTrace();
            }


        }
        return ACCESS_TOKEN;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/8/5
     * @说明: 获取jsapiticket
     */
    public String getjsapiticket(){

        DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/get_jsapi_ticket");
        OapiGetJsapiTicketRequest req = new OapiGetJsapiTicketRequest();
        req.setTopHttpMethod("GET");
        try {
            OapiGetJsapiTicketResponse execute = client.execute(req, getAccessToken());

            return execute.getTicket();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/8/5
     * @说明: 根据code获取用户数据
     */
    public String getUserIdByCode(String code){

        List<OrgManage> org = orgManageMapper.queryId();
        String company = "xoa1001";
        if (org != null && org.size() > 0) {
            company = "xoa" + org.get(0).getOid().toString().trim();
        }
        ContextHolder.setConsumerType(company);

        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
        OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
        request.setCode(code);
        request.setHttpMethod("GET");
        OapiUserGetuserinfoResponse response = null;
        try {
            response = client.execute(request, getAccessToken());
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return response.getUserid();
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/8/5
     * @说明: 获取jsApi鉴权
     */
    public BaseWrapper getjsapi(String url){
        BaseWrapper baseWrapper = new BaseWrapper();

        try{
            SysPara corpIdPara = sysParaMapper.querySysPara("DINGDINGQY_CORPID");
            SysPara agentIdPara = sysParaMapper.querySysPara("DINGDINGQY_AGENTID");

            String ticket = getjsapiticket();
            String nonceStr = "Gsubo";
            Long timeStamp = new Date().getTime();

            String signature = DingTalkJsApiSingnature.getJsApiSingnature(url, nonceStr, timeStamp, ticket);

            Map<String,Object> res = new HashMap<String,Object>();

            res.put("url",url);
            res.put("corpId",corpIdPara.getParaValue());
            res.put("timeStamp",timeStamp);
            res.put("nonceStr",nonceStr);
            res.put("timeStamp",timeStamp);
            res.put("signature",signature);
            res.put("agentId",agentIdPara.getParaValue());

            baseWrapper.setData(res);
            baseWrapper.setFlag(true);
            baseWrapper.setStatus(true);

        }catch (Exception e){
            e.printStackTrace();
        }

        return baseWrapper;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/8/5
     * @说明: 获取钉钉中的部门信息 id为部门id 填写获取指定部门 不填写获取全部部门
     */
    public List<OapiDepartmentListResponse.Department> getDepartments(String id){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
        OapiDepartmentListRequest request = new OapiDepartmentListRequest();
        if(StringUtils.checkNull(id)||"0".equals(id)){
            request.setId(null);
        } else {
            request.setId(id);
        }
        request.setHttpMethod("GET");
        try {
            OapiDepartmentListResponse response = client.execute(request, getAccessToken());

            if(response.getErrcode()==0){
                return response.getDepartment();
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/8/5
     * @说明: 获取指定id部门下的简单用户信息（只包含名字和userid） 不填写获取全部部门下的用户信息(即获取全部信息
     */
    public List<OapiUserSimplelistResponse.Userlist> getUsersByDept(Long offSet ,Long id){

        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/simplelist");
        OapiUserSimplelistRequest request = new OapiUserSimplelistRequest();
        if(id!=null){
            request.setDepartmentId(id);
        }else{
            request.setDepartmentId(1L);
        }
        request.setOffset(offSet);
        request.setSize(100L);
        request.setHttpMethod("GET");

        try {
            OapiUserSimplelistResponse response = client.execute(request, getAccessToken());
            if(response.getErrcode()==0){
                List<OapiUserSimplelistResponse.Userlist> userlist = response.getUserlist();
                if(response.getHasMore()){
                    userlist.addAll(getUsersByDept(++offSet ,id));
                }
                return userlist;
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/8/6
     * @说明: 获取指定部门下的用户详细信息
     */
    public List<OapiUserListbypageResponse.Userlist> getUsersDetailByDept(Long offSet,Long id){

        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/listbypage");
        OapiUserListbypageRequest request = new OapiUserListbypageRequest();
        request.setDepartmentId(id);
        request.setOffset(offSet);
        request.setSize(100L);
        request.setOrder("entry_desc");
        request.setHttpMethod("GET");
        try {
            OapiUserListbypageResponse execute = client.execute(request,getAccessToken());
            if(execute.getErrcode()==0){
                List<OapiUserListbypageResponse.Userlist> userlist = execute.getUserlist();
                if(execute.getHasMore()){
                    userlist.addAll(getUsersDetailByDept(++offSet,id));
                }
                return userlist;
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/8/5
     * @说明: 查询所有用户和绑定状态
     */
    public BaseWrapper selUsersWithBindType(Long deptId){
        BaseWrapper baseWrapper = new BaseWrapper();
        List<OapiUserSimplelistResponse.Userlist> usersByDept = getUsersByDept(0L,deptId);

        List<UserDDMap> userDDMapList = userDDMapMapper.selAllBindUsers();

        Map<String,String> bindMap = new HashMap<String,String>();

        List<UserDingDing> resList = new ArrayList<>();
        for(int i=0,size=userDDMapList.size();i<size;i++){
            UserDDMap userDDMap = userDDMapList.get(i);
            if(userDDMap!=null){
                bindMap.put(userDDMap.getDdUid(),userDDMap.getOaUid());
            }
        }

        for(int i=0,size=usersByDept.size();i<size;i++){
            OapiUserSimplelistResponse.Userlist userlist = usersByDept.get(i);

            // 1.判断是否为空 2.判断钉钉用户的userid是否为空 3.判断是否已经是绑定过的用户
            if(userlist!=null&&!StringUtils.checkNull(userlist.getUserid())&&bindMap.get(userlist.getUserid())==null){
                UserDingDing userDingDing = new UserDingDing();
                userDingDing.setOpenId(userlist.getUserid());
                userDingDing.setUserName(userlist.getName());
                userDingDing.setIfBind("0");
                resList.add(userDingDing);
            } else if(userlist!=null&&bindMap.get(userlist.getUserid())!=null){
                UserDingDing userDingDing = new UserDingDing();
                userDingDing.setOpenId(userlist.getUserid());
                userDingDing.setUserName(userlist.getName());
                userDingDing.setIfBind("1");
                userDingDing.setUserId(bindMap.get(userlist.getUserid()));
                String usernameByUserId = usersMapper.getUsernameByUserId(userDingDing.getUserId());
                if(!StringUtils.checkNull(usernameByUserId)){
                    userDingDing.setBindUserName(usernameByUserId);
                } else {
                    userDingDing.setBindUserName("该用户不存在");
                }
                resList.add(userDingDing);
            }
        }

        baseWrapper.setFlag(true);
        baseWrapper.setStatus(true);
        baseWrapper.setData(resList);

        return baseWrapper;
    }


    /**
     * @作者: 张航宁
     * @时间: 2019/8/5
     * @说明: 钉钉中的用户数据id 绑定OA中的用户
     */
    public BaseWrapper bind(String openId,String userId){

        BaseWrapper baseWrapper = new BaseWrapper();

        if(!StringUtils.checkNull(openId)&&!StringUtils.checkNull(userId)){
            // 根据OaUserId判断是否存在 更新信息
            UserDDMap userid1 = userDDMapMapper.selUserByUserId(userId);
            if (userid1==null) {
                // 根据openId判断是否存在，更新信息
                UserDDMap userDDMap = userDDMapMapper.selUserByOpenId(openId);
                if(userDDMap==null){
                    userDDMap = new UserDDMap();
                    userDDMap.setDdUid(openId);
                    userDDMap.setOaUid(userId);
                    userDDMapMapper.insertSelective(userDDMap);
                } else {
                    userDDMap.setDdUid(openId);
                    userDDMap.setOaUid(userId);
                    userDDMapMapper.updateUserByOpenId(userDDMap);
                }
            }else{
                userid1.setOaUid(userId);
                userid1.setDdUid(openId);
                userDDMapMapper.updateUserByUserId(userid1);
            }

            baseWrapper.setFlag(true);
            baseWrapper.setMsg("绑定成功");
        }else {
            baseWrapper.setFlag(false);
            baseWrapper.setMsg("绑定失败，openId或者userId为空");
        }

        return baseWrapper;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/8/5
     * @说明: 解除绑定
     */
    public BaseWrapper removeBind(String openId,String userId){
        BaseWrapper baseWrapper = new BaseWrapper();

        if(!StringUtils.checkNull(userId)&&!StringUtils.checkNull(openId)){
            userDDMapMapper.deleteByOpenIdOrUserId(openId, userId);
            baseWrapper.setMsg("解绑成功");
            baseWrapper.setFlag(true);
            baseWrapper.setStatus(true);
        }else{
            baseWrapper.setMsg("openId和userId为空，解绑失败");
            baseWrapper.setFlag(false);
        }

        return baseWrapper;
    }

    /**
     * @作者: 张航宁
     * @时间: 2019/8/6
     * @说明: 钉钉组织架构同步
     */
    public BaseWrapper deptSynchro() {
        BaseWrapper wrapper = new BaseWrapper();

        String accessToken = getAccessToken();
        if(StringUtils.checkNull(accessToken)){
            wrapper.setMsg("无法连接到钉钉！");
            return wrapper;
        }
        List<DingdingUpdateDept> updateDept = new ArrayList<>();
        //List<Long> deleteDept = new ArrayList<>();

        //DingdingCreateDept dingdingCreateDept;
        DingdingUpdateDept dingdingUpdateDept;

        String updateResult = "ok";
        String deleteResult = "ok";

        List<Department> deptList = departmentMapper.getDatagrid();

        List<OapiDepartmentListResponse.Department> dingDepartments = getDepartments(null);

        //创建或更新部门
        for(Department department: deptList) {
            boolean create = true;
            boolean update = true;
            //dingdingCreateDept = new DingdingCreateDept();
            dingdingUpdateDept = new DingdingUpdateDept();
            Integer parentid = departmentMapper.getParentDingdingId(department.getDeptId());
            //循环判断部门是否已加入钉钉组织架构
            for(int i = 0; i < dingDepartments.size(); i ++) {
                OapiDepartmentListResponse.Department department1 = dingDepartments.get(i);

                if(String.valueOf(department1.getId()).equals(department.getDingdingDeptId())) {
                    //id存在则已加入钉钉，无需进行创建操作
                    create = false;
                    if((parentid == null||department1.getParentid().intValue() == parentid)
                            &&department1.getName().equals(department.getDeptName())) {
                        //父部门id相同且名字相同则说明信息无变更，无需进行创建操作
                        update = false;
                        break;
                    }
                } else if(department1.getName().equals(department.getDeptName())) {
                    department.setDingdingDeptId(String.valueOf(department1.getId()));
                    departmentMapper.editDept(department);
                    create = false;
                    break;
                }
            }

            if(create) {
                if(department.getDeptName().equals("离职")){
                    continue;
                }
                // 创建部门
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/create");
                OapiDepartmentCreateRequest request = new OapiDepartmentCreateRequest();

                if(department.getDeptParent()==0) {
                    //父部门id为0说明是根部门，设置钉钉父部门id为1
                    request.setParentid("1");
                } else {
                    //设置父部门的钉钉id到钉钉创建类
                    request.setParentid(String.valueOf(parentid));
                }

                request.setCreateDeptGroup(true);
                request.setOrder(department.getDeptNo().substring(department.getDeptNo().length()-3,department.getDeptNo().length()));
                request.setName(department.getDeptName());

                try {
                    OapiDepartmentCreateResponse response = client.execute(request, accessToken);
                    if(response.getErrcode()==0){
                        //写入钉钉部门id
                        department.setDingdingDeptId(response.getId().toString());
                        departmentMapper.editDept(department);
                    }
                } catch (ApiException e) {
                    e.printStackTrace();
                }

            } else if(update) {
                //更新操作
                dingdingUpdateDept.setName(department.getDeptName());
                dingdingUpdateDept.setId(Long.parseLong(department.getDingdingDeptId()));
                dingdingUpdateDept.setParentid(parentid.toString());
                if(department.getDeptNo().length()>2){
                    dingdingUpdateDept.setOrder(department.getDeptNo().substring(department.getDeptNo().length()-3,department.getDeptNo().length()));
                }else{
                    dingdingUpdateDept.setOrder("100");
                }
                updateDept.add(dingdingUpdateDept);
            }
        }

        //钉钉那边有，本地没有则删除该部门   2019-08-06 ps：暂时先放着 以后需要的时候再打开 删除部门操作比较危险 有需求再打开
        /*for(int i = 0; i < dingDepartments.size(); i ++) {
            boolean delete = true;
            for(Department department: deptList) {
                if(dingDepartments.get(i).getId() == department.getDingdingDeptId().longValue()) {
                    delete = false;
                    break;
                }
            }
            if(delete) {
                deleteDept.add(dingDepartments.get(i).getId());
            }
        }*/

        //发送更新部门请求
        for(DingdingUpdateDept sendUpdateDept: updateDept) {

            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/update");
            OapiDepartmentUpdateRequest request = new OapiDepartmentUpdateRequest();
            request.setId(sendUpdateDept.getId());
            request.setParentid(sendUpdateDept.getParentid());
            request.setOrder(sendUpdateDept.getOrder());
            request.setName(sendUpdateDept.getName());

            try {
                client.execute(request, accessToken);
            } catch (ApiException e) {
                e.printStackTrace();
            }

        }

        //发送删除部门请求 2019-08-06 ps：暂时先放着 需要的时候再打开 删除部门比较危险
        /*for(Long id: deleteDept) {
            String deleteRequest = getAccessToken() + "&id=" + id;
            String result = DingDingTool.dingdingRequestGet(DingDingUrl.DINGDING_DELETE_DEPT, deleteRequest);

        }*/

        if(updateResult.equals("ok")&&deleteResult.equals("ok")) {
            wrapper.setFlag(true);
            wrapper.setMsg("同步成功！");
        } else {
            wrapper.setMsg("更新操作结果：" + updateResult + "！<br>删除操作结果：" + deleteResult + "！");
        }
        return wrapper;
    }


    /**
     * @作者: 张航宁
     * @时间: 2019/8/6
     * @说明: 钉钉用户同步接口
     */
    public BaseWrapper userSynchro(String synchroUsers) {
        BaseWrapper wrapper = new BaseWrapper();
        String accessToken = getAccessToken();
        if(StringUtils.checkNull(getAccessToken())){
            wrapper.setMsg("无法连接到钉钉！");
            return wrapper;
        }
        DingdingUser dingdingUser;
        List<Integer> dingdingDeptList;
        String createResult = "ok";
        String updateResult = "ok";
        Integer successNum = 0;
        Integer failedNum = 0;
        String failedReason = "";

        synchroUsers = dealUserSynchroStr(synchroUsers);

        //第一次按部门分开
        for(String deptUsers: synchroUsers.split(";")) {

            //第二次将部门和人员分开
            String dept = deptUsers.split(":")[0];
            String users = deptUsers.split(":")[1];

            Integer dingdingDeptId = departmentMapper.getDingdingIdByDeptId(Integer.parseInt(dept));

            if(dingdingDeptId==0) {
                wrapper.setMsg("选中人员所在部门未同步到钉钉，请先同步组织结构！");
                wrapper.setFlag(false);
                return wrapper;
            }

            List<OapiUserListbypageResponse.Userlist> usersByDept = getUsersDetailByDept(0L,dingdingDeptId.longValue());

            //第三次将人员分开
            for(String user: users.split(",")) {
                Users theUser = usersMapper.getByUserId(user);
                dingdingUser = new DingdingUser();
                dingdingDeptList = new ArrayList<>();
                String result = "";
                UserDDMap userDDMap = new UserDDMap();
                userDDMap.setOaUid(theUser.getUserId());

                //创建更新人员
                dingdingDeptList.add(dingdingDeptId);
                dingdingUser.setDepartment(dingdingDeptList);
                dingdingUser.setEmail(theUser.getEmail());
                dingdingUser.setMobile(theUser.getMobilNo());
                dingdingUser.setName(theUser.getUserName());
                dingdingUser.setPosition(theUser.getPost());

                if(StringUtils.checkNull(dingdingUser.getName())||StringUtils.checkNull(dingdingUser.getMobile())) {
                    failedNum ++;
                    if(!failedReason.contains("、人员未设置电话号码")){
                        failedReason += "、人员未设置电话号码";
                    }
                    continue;
                }

                if(usersByDept.size() > 0) {
                    for(int i = 0; i < usersByDept.size(); i ++) {
                        OapiUserListbypageResponse.Userlist userlist = usersByDept.get(i);
                        //userId相同，说明存在
                        if(theUser.getUserId().equals(userlist.getUserid())) {
                            //如果有一个信息不相同，则更新。
                            if(!userlist.getName().equals(theUser.getUserName())||
                                    !userlist.getMobile().equals(theUser.getMobilNo())||
                                    !userlist.getPosition().equals(theUser.getPost())||
                                    !userlist.getEmail().equals(theUser.getEmail())){

                                // 更新
                                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/update");
                                OapiUserUpdateRequest request = new OapiUserUpdateRequest();

                                request.setName(dingdingUser.getName());
                                request.setMobile(dingdingUser.getMobile());
                                request.setEmail(dingdingUser.getEmail());
                                request.setPosition(dingdingUser.getPosition());

                                try {
                                    client.execute(request, getAccessToken());
                                } catch (ApiException e) {
                                    e.printStackTrace();
                                }

                            }
                            userDDMap.setDdUid(dingdingUser.getUserid());
                        } else {
                            // 新建
                            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/create");
                            OapiUserCreateRequest request = new OapiUserCreateRequest();
                            request.setMobile(dingdingUser.getMobile());
                            request.setName(dingdingUser.getName());
                            request.setEmail(dingdingUser.getEmail());
                            request.setPosition(dingdingUser.getPosition());
                            // 需要用字符串， "[100,200]" 这种格式
                            List<Long> departments = new ArrayList<Long>();
                            departments.add(dingdingUser.getDepartment().get(0).longValue());
                            request.setDepartment(JSON.toJSONString(departments));

                            try {
                                OapiUserCreateResponse response = client.execute(request, getAccessToken());
                                if(response.getErrcode()==0){
                                    // 设置绑定信息
                                    userDDMap.setDdUid(response.getUserid());
                                }
                            } catch (ApiException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                } else {
                    // 新建
                    DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/create");
                    OapiUserCreateRequest request = new OapiUserCreateRequest();
                    request.setMobile(dingdingUser.getMobile());
                    request.setName(dingdingUser.getName());
                    request.setEmail(dingdingUser.getEmail());
                    request.setPosition(dingdingUser.getPosition());
                    // 需要用字符串， "[100,200]" 这种格式
                    List<Long> departments = new ArrayList<Long>();
                    departments.add(dingdingUser.getDepartment().get(0).longValue());
                    request.setDepartment(JSON.toJSONString(departments));

                    try {
                        OapiUserCreateResponse response = client.execute(request, getAccessToken());
                        if(response.getErrcode()==0){
                            // 设置绑定信息
                            userDDMap.setDdUid(response.getUserid());
                        }
                    } catch (ApiException e) {
                        e.printStackTrace();
                    }
                }
                if(!createResult.equals("ok")||!updateResult.equals("ok")) {
                    failedNum ++;
                    /*if(!failedReason.contains("、" + getErrmsg(result))) {
                        failedReason += "、" + getErrmsg(result);
                    }*/
                } else {
                    successNum ++;
                    if(userDDMapMapper.getUserDDMapByUserId(theUser.getUserId())==null) {
                        userDDMapMapper.insert(userDDMap);
                    }
                }
            }
        }

        if(failedReason.contains("、")) {
            failedReason = failedReason.replaceFirst("、", "");
            failedReason += "。";
        }
        String result = "成功：" + successNum + "个，失败：" + failedNum + "个";
        if(failedNum > 0) {
            result += "，失败原因：" + failedReason;
        }
        wrapper.setMsg(result);
        wrapper.setFlag(true);
        return wrapper;
    }











    /**
     * @作者: 张航宁
     * @时间: 2019/8/6
     * @说明: 钉钉用户同步 拆分工具方法
     */
    public String dealUserSynchroStr(String synchroUsers) {
        String result = ",";
        Integer deptId = 0;

        for(String one: synchroUsers.split(";")) {
            Integer nowDeptId = Integer.parseInt(one.split(",")[0]);
            String uid = one.split(",")[1];

            if (deptId == nowDeptId) {
                result += uid + ",";
            } else {
                result = result.substring(0, result.length() - 1);
                result += ";" + nowDeptId + ":" + uid + ",";
                deptId = nowDeptId;
            }
        }
        result = result.replaceFirst(";", "");
        result = result.substring(0, result.length() - 1);
        return result;
    }

}
